package notityStartCenter

import (
	"7qule.com/sd3/CrossServer/src/utils"
	"fmt"

	"7qule.com/sd3/CrossServer/src/common/onlinelog"
	"7qule.com/sd3/CrossServer/src/common/systemConstant"
	"public.com/Framework/goroutineMgr"
	"public.com/Framework/logMgr"
	"public.com/goutil/debugUtil"
	"public.com/goutil/syncUtil"
)

// 启动时main方法执行，是一次性方法，用于通知各个模块的初始化
var (
	// key:初始化成功的标志名称   val:占位符
	registerMap = make(map[string]chan bool)
	mutex       = syncUtil.NewRWLocker()
)

// 注册需要被通知的对象
// name:唯一标识
// ch:用于通知的通道
func Register(chanName string, ch chan bool) {
	if isOk, prevStack, currStack := mutex.Lock(systemConstant.DeathLockTime); isOk == false {
		//记日志
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
	}
	defer mutex.Unlock()
	if _, exists := registerMap[chanName]; exists {
		panic(fmt.Errorf("registerMap.Register-%s已经存在，请检查", chanName))
	}

	registerMap[chanName] = ch
	logMgr.DebugLog(fmt.Sprintf("notityCenter.Register-%s，当前共有%d个注册", chanName, len(registerMap)), "")
}

// 取消启动成功通知注册
// name:唯一标识
func Unregister(name string) {
	if isOk, prevStack, currStack := mutex.Lock(systemConstant.DeathLockTime); isOk == false {
		//记日志
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
	}
	defer mutex.Unlock()

	delete(registerMap, name)
}

// 通知所有已注册的对象
func Notify() {
	// 处理goroutine数量
	goroutineName := "notityStartCenter.Notify"
	goroutineMgr.Monitor(goroutineName)
	defer goroutineMgr.ReleaseMonitor(goroutineName)
	defer utils.LogErrorRecover()

	if isOk, prevStack, currStack := mutex.RLock(systemConstant.DeathLockTime); isOk == false {
		//记日志
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
	}
	defer mutex.RUnlock()

	println("notityStartCenter.Notify")
	for name, ch := range registerMap {
		ch <- true
		msg := fmt.Sprintf("通知:%s初始化成功", name)
		debugUtil.Println(msg)
		logMgr.DebugLog(msg, "")
	}
}
